package com.lu.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.lu.api.schedule.IScheduleClient;
import com.lu.model.common.dtos.ResponseResult;
import com.lu.model.common.enums.TaskTypeEnum;
import com.lu.model.schedule.dto.Task;
import com.lu.model.wemedia.pojo.WmNews;
import com.lu.utils.common.ProtostuffUtil;
import com.lu.wemedia.service.WmNewsAutoTaskService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Slf4j
@Service
@Transactional
public class WmNewsAutoTaskServiceImpl implements WmNewsAutoTaskService {

    @Autowired
    private IScheduleClient scheduleClient;
    @Autowired
    private WmNewsAutoExamineServiceImpl wmNewsAutoExamineService;

    /**
     * 文章发布添加延时任务队列
     * @param id
     * @param publishTime
     */
    @Override
    @Async
    public void addNewsToTsk(Integer id, Date publishTime) {
        log.info("开始添加文章发布任务到延时队列");
        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        scheduleClient.addTask(task);
        log.info("文章发布任务已添加到延时队列");
        log.info("{}的发布时间为{}", wmNews.getId(), wmNews.getPublishTime());
    }


    /**
     * 消费延时队列任务
     */
    @Scheduled(fixedDelay = 1000)
    @Override
    @SneakyThrows
    public void consumeTask() {
        log.info("从延时队列拉取任务审核发布文章");
        ResponseResult responseResult = scheduleClient.pullTask(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (responseResult.getCode().equals(200) && responseResult.getData() != null) {
            String content = JSON.toJSONString(responseResult.getData());
            Task task = JSON.parseObject(content, Task.class);
            byte[] parameters = task.getParameters();
            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
            System.out.println("当前发布审核的文章是" + wmNews.getId());
            wmNewsAutoExamineService.autoExamine(wmNews.getId());
        }
        log.info("该任务已经消费完毕!");
    }
}
